package com.weatherapp.simple;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.weatherapp.simple.adapter.DailyWeatherAdapter;
import com.weatherapp.simple.adapter.HourlyWeatherAdapter;
import com.weatherapp.simple.model.DailyWeather;
import com.weatherapp.simple.model.HourlyWeather;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    
    private static final int REQUEST_CODE_CITY_SELECTION = 1001;
    private String currentCity = "北京";
    private boolean isCelsius = true; // 温度单位：true为摄氏度，false为华氏度

    private TextView tvCityName;
    private TextView tvCurrentTemperature;
    private TextView tvCurrentWeatherIcon;
    private TextView tvCurrentWeatherDesc;
    private ImageView ivMenu;
    private ImageView ivRefresh;
    private RecyclerView rvHourlyWeather;
    private RecyclerView rvDailyWeather;
    
    private HourlyWeatherAdapter hourlyAdapter;
    private DailyWeatherAdapter dailyAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        initViews();
        setupRecyclerViews();
        loadSettings();
        loadMockData();
        setupClickListeners();
    }

    private void initViews() {
        tvCityName = findViewById(R.id.tv_city_name);
        tvCurrentTemperature = findViewById(R.id.tv_current_temperature);
        tvCurrentWeatherIcon = findViewById(R.id.tv_current_weather_icon);
        tvCurrentWeatherDesc = findViewById(R.id.tv_current_weather_desc);
        ivMenu = findViewById(R.id.iv_menu);
        ivRefresh = findViewById(R.id.iv_refresh);
        rvHourlyWeather = findViewById(R.id.rv_hourly_weather);
        rvDailyWeather = findViewById(R.id.rv_daily_weather);
    }

    private void setupRecyclerViews() {
        // 设置横向滚动的 RecyclerView
        LinearLayoutManager hourlyLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        rvHourlyWeather.setLayoutManager(hourlyLayoutManager);
        
        LinearLayoutManager dailyLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        rvDailyWeather.setLayoutManager(dailyLayoutManager);
        
        // 初始化适配器
        hourlyAdapter = new HourlyWeatherAdapter(new ArrayList<>());
        dailyAdapter = new DailyWeatherAdapter(new ArrayList<>());
        
        rvHourlyWeather.setAdapter(hourlyAdapter);
        rvDailyWeather.setAdapter(dailyAdapter);
    }

    private void loadMockData() {
        // 使用统一的城市数据加载方法，确保温度单位设置生效
        loadMockDataForCity(currentCity);
    }

    private void loadSettings() {
        SharedPreferences sharedPreferences = getSharedPreferences("weather_settings", MODE_PRIVATE);
        isCelsius = sharedPreferences.getBoolean("is_celsius", true);
    }

    private void setupClickListeners() {
        // 菜单按钮点击事件
        ivMenu.setOnClickListener(v -> showMenuPopup(v));
        
        // 刷新按钮点击事件
        ivRefresh.setOnClickListener(v -> refreshWeatherData());
    }

    private void showMenuPopup(View view) {
        PopupMenu popup = new PopupMenu(this, view);
        popup.getMenuInflater().inflate(R.menu.main_menu, popup.getMenu());
        
        popup.setOnMenuItemClickListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.menu_city_management) {
                Intent intent = new Intent(MainActivity.this, CityManagementActivity.class);
                startActivityForResult(intent, REQUEST_CODE_CITY_SELECTION);
                return true;
            } else if (itemId == R.id.menu_settings) {
                startActivity(new Intent(MainActivity.this, SettingsActivity.class));
                return true;
            }
            return false;
        });
        
        popup.show();
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == REQUEST_CODE_CITY_SELECTION && resultCode == RESULT_OK) {
            if (data != null) {
                String selectedCity = data.getStringExtra("selected_city");
                if (selectedCity != null) {
                    updateWeatherForCity(selectedCity);
                }
            }
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 当从设置页面返回时，重新加载设置并更新显示
        loadSettings();
        loadMockData();
    }
    
    private void updateWeatherForCity(String cityName) {
        currentCity = cityName;
        tvCityName.setText(cityName);
        loadMockDataForCity(cityName);
    }
    
    private void loadMockDataForCity(String cityName) {
        // 根据城市名称加载不同的模拟天气数据
        int celsiusTemp = 25;
        String weatherIcon = "☀️";
        String weatherDesc = "晴";
        
        switch (cityName) {
            case "北京":
                celsiusTemp = 25;
                weatherIcon = "☀️";
                weatherDesc = "晴";
                break;
            case "上海":
                celsiusTemp = 22;
                weatherIcon = "⛅";
                weatherDesc = "多云";
                break;
            case "广州":
                celsiusTemp = 28;
                weatherIcon = "🌧️";
                weatherDesc = "小雨";
                break;
            case "深圳":
                celsiusTemp = 27;
                weatherIcon = "🌥️";
                weatherDesc = "阴";
                break;
            case "杭州":
                celsiusTemp = 24;
                weatherIcon = "☀️";
                weatherDesc = "晴";
                break;
            case "成都":
                celsiusTemp = 23;
                weatherIcon = "☀️";
                weatherDesc = "晴";
                break;
            case "西安":
                celsiusTemp = 20;
                weatherIcon = "⛅";
                weatherDesc = "多云";
                break;
            case "南京":
                celsiusTemp = 21;
                weatherIcon = "🌧️";
                weatherDesc = "小雨";
                break;
            case "武汉":
                celsiusTemp = 26;
                weatherIcon = "☀️";
                weatherDesc = "晴";
                break;
            case "重庆":
                celsiusTemp = 29;
                weatherIcon = "🌧️";
                weatherDesc = "小雨";
                break;
            case "天津":
                celsiusTemp = 23;
                weatherIcon = "⛅";
                weatherDesc = "多云";
                break;
            default:
                celsiusTemp = 25;
                weatherIcon = "☀️";
                weatherDesc = "晴";
                break;
        }
        
        // 根据温度单位设置显示温度
        if (isCelsius) {
            tvCurrentTemperature.setText(celsiusTemp + "°C");
        } else {
            int fahrenheitTemp = celsiusToFahrenheit(celsiusTemp);
            tvCurrentTemperature.setText(fahrenheitTemp + "°F");
        }
        tvCurrentWeatherIcon.setText(weatherIcon);
        tvCurrentWeatherDesc.setText(weatherDesc);
        
        // 更新逐小时预报数据（根据城市微调）
        List<HourlyWeather> hourlyList = new ArrayList<>();
        String[] times = {"14:00", "15:00", "16:00", "17:00", "18:00", "19:00", 
                         "20:00", "21:00", "22:00", "23:00", "0:00", "1:00", "2:00"};
        
        // 根据城市调整温度范围
        int baseTemp = 25;
        switch (cityName) {
            case "广州": case "深圳": case "重庆":
                baseTemp = 28;
                break;
            case "上海": case "杭州": case "成都": case "天津":
                baseTemp = 23;
                break;
            case "西安": case "南京":
                baseTemp = 21;
                break;
            case "武汉":
                baseTemp = 26;
                break;
            default:
                baseTemp = 25;
        }
        
        int[] temperatures = {baseTemp, baseTemp+1, baseTemp+1, baseTemp, baseTemp-2, baseTemp-3, 
                             baseTemp-4, baseTemp-5, baseTemp-6, baseTemp-7, baseTemp-8, baseTemp-9, baseTemp-10};
        
        // 根据温度单位转换温度
        if (!isCelsius) {
            for (int i = 0; i < temperatures.length; i++) {
                temperatures[i] = celsiusToFahrenheit(temperatures[i]);
            }
        }
        
        String[] icons = {"☀️", "☀️", "⛅", "⛅", "🌙", "🌙", 
                         "🌙", "🌙", "🌙", "🌙", "🌙", "🌙", "🌙"};
        String[] descriptions = {"晴", "晴", "多云", "多云", "晴", "晴", 
                                "晴", "晴", "晴", "晴", "晴", "晴", "晴"};
        
        for (int i = 0; i < 12; i++) {
            hourlyList.add(new HourlyWeather(times[i], icons[i], temperatures[i], descriptions[i]));
        }
        
        // 更新未来天气预报数据
        List<DailyWeather> dailyList = new ArrayList<>();
        // 根据城市调整温度范围
        int dailyBaseTemp = baseTemp + 1;
        int[] highTemps = {dailyBaseTemp+1, dailyBaseTemp, dailyBaseTemp-5, dailyBaseTemp-3, dailyBaseTemp+3, dailyBaseTemp+1, dailyBaseTemp-2};
        int[] lowTemps = {dailyBaseTemp-7, dailyBaseTemp-8, dailyBaseTemp-10, dailyBaseTemp-9, dailyBaseTemp-6, dailyBaseTemp-7, dailyBaseTemp-11};
        
        // 根据温度单位转换温度
        if (!isCelsius) {
            for (int i = 0; i < highTemps.length; i++) {
                highTemps[i] = celsiusToFahrenheit(highTemps[i]);
                lowTemps[i] = celsiusToFahrenheit(lowTemps[i]);
            }
        }
        
        dailyList.add(new DailyWeather("周一", "10/14", "☀️", "晴", highTemps[0], lowTemps[0]));
        dailyList.add(new DailyWeather("周二", "10/15", "⛅", "多云", highTemps[1], lowTemps[1]));
        dailyList.add(new DailyWeather("周三", "10/16", "🌧️", "小雨", highTemps[2], lowTemps[2]));
        dailyList.add(new DailyWeather("周四", "10/17", "🌥️", "阴", highTemps[3], lowTemps[3]));
        dailyList.add(new DailyWeather("周五", "10/18", "☀️", "晴", highTemps[4], lowTemps[4]));
        dailyList.add(new DailyWeather("周六", "10/19", "⛅", "多云", highTemps[5], lowTemps[5]));
        dailyList.add(new DailyWeather("周日", "10/20", "🌦️", "小雨", highTemps[6], lowTemps[6]));
        
        hourlyAdapter.updateData(hourlyList);
        dailyAdapter.updateData(dailyList);
    }

    private void refreshWeatherData() {
        // 重新加载设置和天气数据
        loadSettings();
        loadMockData();
    }
    
    private int celsiusToFahrenheit(int celsius) {
        return (int) Math.round(celsius * 9.0 / 5.0 + 32);
    }
}